package edu.ccut.saturn.workflow.common;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.operation.Operation;

public class GetVersionBYWfKey extends DefaultComponent {

	@SuppressWarnings("unchecked")
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		String wfKey = (String) parameterContext.getParameterValue(0);
		Connection conn = parameterContext.getConnection();
		String version = getAvailabilityVersion(conn, wfKey);
		parameterContext.setParameter(1, version);
	}

	/**
	 * 获得有效版本
	 * 
	 * @param conn
	 * @param wfKey
	 * @return
	 * @throws SQLException
	 */
	private String getAvailabilityVersion(Connection conn, String wfKey)
			throws Exception {
		String version = null;
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("process_xml_key", wfKey);

		ArrayList<SaturnData> processDefList = Operation.dataBase()
				.queryBySaturnSql(Constants.SATURNDATA_WF_PROCESS_DEFINE,
						"GET_AVAILABILITY_DEFINE", paramMap, conn);

		if (processDefList != null) {
			version = processDefList.get(0).get("version") + "";
		}

		return version;
	}

	/**
	 * 获得有效版本
	 * 
	 * @param conn
	 * @param wfKey
	 * @return
	 * @throws SQLException
	 */
	/*
	 * private String getYouXiaoMaxVersion(Connection conn,String wfKey) throws
	 * SQLException{ double yxtime=0.0; String version = ""; Statement stm =
	 * null; ResultSet rs = null; try{ stm = conn.createStatement(); String sql
	 * ="select sysdate-t.inuredate, version from wf_process_define t" + " where
	 * t.process_xml_key=" +"'"+wfKey+"'"+ " and t.version=(select max(version)
	 * from wf_process_define)"; rs = stm.executeQuery(sql); if(rs.next()){
	 * yxtime = rs.getDouble(1); version = rs.getString(2); } }finally{
	 * rs.close(); stm.close(); } if(yxtime>0){ return version; }else{ return
	 * getYouXiaoVersion(conn,wfKey); } }
	 * 
	 *//**
		 * 获得第二大版本
		 * 
		 * @param conn
		 * @param wfKey
		 * @return
		 * @throws SQLException
		 */
	/*
	 * private String getYouXiaoVersion(Connection conn,String wfKey) throws
	 * SQLException{ String version = ""; Statement stm = null; ResultSet rs =
	 * null; try{ stm = conn.createStatement(); String sql ="select max(version)
	 * from wf_process_define" + " where process_xml_key="+"'"+wfKey+"'" + " and
	 * version<>(select max(version) from wf_process_define)"; rs =
	 * stm.executeQuery(sql); if(rs.next()){ version = rs.getString(1); }
	 * }finally{ rs.close(); stm.close(); } return version; }
	 */
}
